package com.example.android.miwok;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {
    // Create a media player object
    private MediaPlayer mMediaPlayer;
    private AudioManager mAudioManager;
    private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                    focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                mMediaPlayer.pause();
                mMediaPlayer.seekTo(0);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                mMediaPlayer.start();
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                releaseMediaPlayer();
            }
        }
    };
    // 检测播放是否结束
    private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            releaseMediaPlayer();
            //Toast.makeText(NumbersActivity.this, "IM Done", Toast.LENGTH_SHORT).show();
        }

    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_list);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // Initial words list in ArrayList
        final ArrayList<Word> words = new ArrayList<Word>() {{
            String[] miWorkWords = {"一", "二", "三", "四", "五", "六", "七",
                    "八", "九", "十"};
            String[] defaultWords = {"one", "two", "three", "four", "five",
                    "six", "seven", "eight", "nine", "ten"};
            int[] numberImages = {R.drawable.number_one, R.drawable.number_two, R.drawable.number_three,
                    R.drawable.number_four, R.drawable.number_five, R.drawable.number_six, R.drawable.number_seven,
                    R.drawable.number_eight, R.drawable.number_nine, R.drawable.number_ten};
            int[] numberAudios = {R.raw.number_one, R.raw.number_two, R.raw.number_three,
                    R.raw.number_four, R.raw.number_five, R.raw.number_six, R.raw.number_seven,
                    R.raw.number_eight, R.raw.number_nine, R.raw.number_ten};

            int index = 0;
            while (index < miWorkWords.length) {
                Word w = new Word(miWorkWords[index], defaultWords[index], numberImages[index], numberAudios[index]);
                add(w);
                index++;
            }
        }};

//        // Here is test method
//        for (int i = 1; i < words.size(); i++) {
//            Log.v("MainActivity", words.get(i - 1));
//        }

//        // Find rootView
//        LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);
//        // Create a word TextView in loops
//        for (int i = 0; i < words.size(); i++) {
//            TextView textView = new TextView(this);
//            textView.setText(words.get(i));
//            rootView.addView(textView);
//        }

        // Create a ArrayAdapter
        WordAdapter itemAdapter = new WordAdapter(this, words, R.color.category_numbers);

        final ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(itemAdapter);

        //  add listView onClickListener method
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Release the media player if it currently exists because we are about to
                // play a different sound file
                releaseMediaPlayer();

                // Search the certain position in your words list
                Word word = words.get(position);

                Log.v("NumbersActivity", "Current word: " + word);

//                mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId());
//                mMediaPlayer.start();

                // Requesting for AudioFocus
                int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                        AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                    mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId());
                    mMediaPlayer.start();
                    mMediaPlayer.setOnCompletionListener(mCompletionListener);
                }


            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
        releaseMediaPlayer();
    }

    /**
     * Clean up the media player by releasing its resources.
     */
    private void releaseMediaPlayer() {
        // If the media player is not null, then it may be currently playing a sound.
        if (mMediaPlayer != null) {
            // Regardless of the current state of the media player, release its resources
            // because we no longer need it.
            mMediaPlayer.release();

            // Set the media player back to null. For our code, we've decided that
            // setting the media player to null is an easy way to tell that the media player
            // is not configured to play an audio file at the moment.
            mMediaPlayer = null;

            // When finished playing, we don't need focus anymore.
            mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
        }
    }

}
